<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

use think\model\concern\SoftDelete;

class ArticleCate extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    //use SoftDelete;

    protected $deleteTime = 'deleted_at';

    // 软删除字段默认值
    protected $defaultSoftDelete = 0;

    // 当前模型名称 不带前缀
    protected $name = 'article_cate';

    public $pk = 'id';


    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = (new self())->formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        return $item;
    }

    /**
     * 是否被使用过
     */
    public static function isUsed($id)
    {
        if (!$id) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有下级
        $child = self::where('parent_id', $id)->field('id, status')->find();
        if ($child) {
            return ['code' => 0, 'msg' => '该分类有下级分类，请先删除下级分类'];
        }
        // 是否有文章
        $articleWhere = [
            ['a.cate_id', '=', $id],
        ];
        $article = \app\common\model\Article::alias('a')->where($articleWhere)->field('a.id, a.status')->find();
        if ($article) {
            if ($article['status'] != 90) {
                return ['code' => 0, 'msg' => '该分类下有文章，请先删除文章'];
            }
            return ['code' => 2, 'msg' => '该分类下有已删除的文章'];
        }

        return ['code' => 1, 'msg' => ''];
    }
}
